/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.approval;

import com.alibaba.fastjson.JSONObject;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.institution.bean.*;
import com.koron.institution.mapper.*;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ConformanceAuditService implements AfterApprovalService {

    private final static  Logger logger = LoggerFactory.getLogger(InstitutionAddService.class);

    private static ConformanceAssessment translate(ConformanceAssessmentHistory history) {
        ConformanceAssessment assessment = new ConformanceAssessment();
        assessment.setCorpCode(history.getCorpCode());
        assessment.setConformanceYear(history.getConformanceYear());
        assessment.setInstitutionId(history.getInstitutionId());
        assessment.setInstitutionCode(history.getInstitutionCode());
        assessment.setInstitutionFileCode(history.getInstitutionFileCode());
        assessment.setInstitutionFileName(history.getInstitutionFileName());
        assessment.setPublicationDate(history.getPublicationDate());
        assessment.setExecutionDate(history.getExecutionDate());
        assessment.setApplicableProvisions(history.getApplicableProvisions());
        assessment.setRemark(history.getRemark());
        assessment.setVersion(history.getVersion());
        assessment.setAttachment(history.getAttachment());
        assessment.setConformanceFlag(history.getConformanceFlag());
        assessment.setSuitDept(history.getSuitDept());
        assessment.setAddUser(history.getAddUser());
        assessment.setUpdateUser(history.getUpdateUser());
        assessment.setAddTime(history.getAddTime());
        assessment.setUpdateTime(history.getUpdateTime());
        assessment.setAddUserName(history.getAddUserName());
        assessment.setUpdateUserName(history.getUpdateUserName());
        return assessment;
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            List<String> buId = new ArrayList<>();
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        ConformanceAssessment assessment = translate(history);
                        assessment.setState(2);
                        if (history != null) {
                            ConformanceAssessment conformanceAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if(conformanceAssessment!=null){
                                conformanceAssessment.setState(0);
                                mapper.updateByPrimaryKeySelective(conformanceAssessment);
                            }
                            history.setState(0);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            //查询是否为任务
            if (StringUtils.isNotBlank(audit.getOtherBusinessIds())) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                JobsTasks jobsTasks = jobsTasksMapper.queryById(audit.getOtherBusinessIds());
                if (jobsTasks != null) {
                    Date commitDate = jobsTasks.getCompletedTime();
                    if (commitDate == null) {
                        jobsTasks.setCompletedTime(audit.getAddTime());
                    }
                    if (commitDate.after(jobsTasks.getEndTime())) {
                        jobsTasks.setState(2);
                    } else {
                        jobsTasks.setState(1);
                    }
//                    jobsTasks.setBusinessId(new Gson().toJson(buId));
                    jobsTasks.setFstatusflag(2);
                    jobsTasksMapper.completed(jobsTasks);
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            List<String> buId = new ArrayList<>();
            if (idList != null && !idList.isEmpty()) {
                ConformanceAssessmentHistoryMapper historyMapper = factory.getMapper(ConformanceAssessmentHistoryMapper.class);
                ConformanceAssessmentMapper mapper = factory.getMapper(ConformanceAssessmentMapper.class);
                for (String id : idList) {
                    if (StringUtils.isNotBlank(id)) {
                        ConformanceAssessmentHistory history = historyMapper.selectByPrimaryKey(id);
                        ConformanceAssessment assessment = translate(history);
                        assessment.setState(2);
                        if (history != null) {
                            ConformanceAssessment conformanceAssessment = mapper.selectByPrimaryKey(history.getOldId());
                            if (conformanceAssessment != null) {
                                conformanceAssessment.setState(5);
                                mapper.updateByPrimaryKeySelective(conformanceAssessment);
                            }
                            history.setState(4);
                            history.setHistoryFlag(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
